use crate::rediswrapper::oper;
use actix_web::{  HttpMessage};

pub const TICKET_COOKIE_NAME: &'static str = "cas-ticket";
pub const REDIS_KEY_PREFIX: &'static str = "cas::cas-ticket";
use std::env;
use urlencoding::encode;
//是否已登录
pub async fn is_logined(req: &actix_web::dev::ServiceRequest) -> bool {
    if let Some(cookie) = req.cookie(&TICKET_COOKIE_NAME) {//先看cookie有没有ticket
        let ticket = cookie.value();
        let key = format!("{}-{}",REDIS_KEY_PREFIX, &ticket);
        //看看redis有没有存储验证信息
        if let Some(info) = oper::get_key_val(&key).await {
            true
        } else {
            false
        }
    } else {
       false
    }
}
//通过ticket从redis获取已登录信息
pub async fn get_logined_info_from_redis_by_ticket(ticket: &str) -> Option<String> {
    let key = format!("{}-{}",REDIS_KEY_PREFIX, &ticket);
    oper::get_key_val(&key).await
}

//根据ticket获取信息存入redis
pub async fn set_logined_info_into_redis_by_ticket(
    ticket: &str, /*令牌*/
    url: &String,    /*访问地址*/
) {
    //cas验证地址
    let cas_url = env::var("CAS_VALID_URL").unwrap();
    //获取验证信息的URL
    let validate_url = format!(
        "{}/validate?service={}&ticket={}&renew=false",
        cas_url.to_owned(),
        encode(url),
        ticket.to_owned()
    );

    println!("validate_url={}",&validate_url);

    let validate_response = reqwest::Client::builder()
    .danger_accept_invalid_certs(true)
    .build()
    .expect("client builder").get(&validate_url).send()
    .unwrap().text().unwrap();

    let key = format!("{}-{}",REDIS_KEY_PREFIX, &ticket);

    println!("validate_response={}",&validate_response);
    oper::set_key_val(&key, &validate_response).await
}
//验证跳转链接
pub fn get_redirect_url(  url: &String) -> String {
    //cas登录地址
    let cas_url = env::var("CAS_LOGIN_URL").unwrap();
    //来源系统标记
    let cas_srcsys = env::var("CAS_SRCSYS").unwrap();
    format!(
        "{}?srcsys={}&service={}",
        cas_url.to_owned(),
        cas_srcsys.to_owned(),
        encode(url)
    )

}
